<?php
/**
 * 分布式数据库的应用
 */
class MysqldataAction extends actionMiddleware
{   
    
    public function index(){
        extract($this->input);
        if($isPost){
            $name = isset($name)?$name:'';
            $age = isset($age)?$age:'';
            
            $data = array('name'=>$name,'age'=>$age);
            $insert_id = M('user')->add($data);//先给主库添加数据，获取到add的id
            
            if($insert_id>0){
                $data['user_id'] = $insert_id;
                $insert_id = M('user')->add($data,$insert_id);//根据从主库获取的id给分库添加数据
                if($insert_id){
                    $this->redirect('用户添加成功', Root.'mysqldata/index/');
                }
            }
        }
       $this->display('mysqldata/add.php');
    }
    
    /**
     * 从分库查询数据
     */
    public function find(){
        $user_id = 1;
        $rule['exact']['user_id'] = $user_id;
        $rule['slice'] = $user_id;
        $data = M('user')->findOne($rule,'name,age','0');
        var_dump($data);
    }
    
    /**
     * 编辑用户，先编辑分库，然后把编辑的sql压入队列，通过计划任务同步数据
     */
    public function edit(){
        extract($this->input);
        $user_id = isset($user_id)?$user_id:0;
        $data = array('name'=>'你是?');
        $_rule['exact']['user_id'] = $user_id;
        $_rule['slice'] = $user_id;//如果有slice这个参数那么就去分库编辑数据
        $re = M('user')->edit($data,$_rule);
        if($re){
            $sql = get_update_sql('user', $data, $_rule);
            $redis_suss = lpushVal('core_sql', $sql);//数据加入队列
            var_dump($sql);
            var_dump($redis_suss);
        }
    }
    
    public function delete(){
        extract($this->input);
        $user_id = isset($user_id)?$user_id:'';
        $rule['exact']['user_id'] = $user_id;
        $rule['slice'] = $user_id;
        $res = M('user')->del($rule);
        if($res){
            $sql = get_delete_sql('user', $rule);
            lpushVal('core_sql', $sql);
        }
        var_dump($sql);
    }
    
}

